<!-- 获取省市区 -->
<template>
  <el-cascader :props="propsCascader" ref="cascader" clearable v-model="selectedOptions" :placeholder="placeholder"></el-cascader>
</template>

<script>
  import {
    provinceList,
    cityList,
    areaList
  } from '@/services/model/common'
  export default {
    props: {
      placeholder: {
        type: String,
        default: '请选择'
      }
    },
    computed: {
      selectedOptions: {
        get (val) {
          if (val.$attrs.value) {
            return val.$attrs.value.split('-') || []
          } else {
            return []
          }
        },
        set (val) {
          this.newOptions = val.join('-')
          this.$emit('input', this.newOptions)
        }
      }
    },
    data () {
      return {
        test: [],
        newOptions: '',
        propsCascader: {
          lazy: true,
          label: 'name',
          value: 'code',
          lazyLoad (node, resolve) {
            const {
              level,
              data
            } = node
            if (level === 0) {
              provinceList().then(res => {
                const {
                  data
                } = res
                resolve(data)
              })
            } else if (level === 1) {
              cityList({
                provinceCode: data.code
              }).then(res => {
                const {
                  data
                } = res
                resolve(data)
              })
            } else if (level === 2) {
              areaList({
                cityCode: data.code
              }).then(res => {
                const data = res.data.map(x => ({
                  ...x,
                  leaf: true
                }))
                resolve(data)
              })
            } else {
              resolve([])
            }
          }
        },
      }
    },
  }
</script>

<style>
</style>
